#!/bin/bash

# ----------------------------------------------------------------------
# Filename:   rules.sh
# Version:    1.0
# Date:       2013/12/05
# Author:     huijing.hei
# Email:      huijing.hei@cs2c.com.cn
# Summary:    03系统安全功能-03IPTables-02IPTables基本策略和简单规则配置-02规则查询
# Notes:       ***
# Copyright:    China Standard Software Co., Ltd.
# History：     
#             Version 1.0, 2013/12/05
#             - iptables -L.
# ----------------------------------------------------------------------

##! @TODO:  iptables start
##! @AUTHOR: huijing.hei
##! @VERSION: 1.0 
##! @OUT: 0 => success; 1 => failure

function DoSetup()
{
    trap DoCleanup INT EXIT
    serv=iptables
    CheckServiceExists  ${serv}
    EchoResult "check service"

#    StatusDaemon ${serv}
#
#    # start
#    if [ $? -ne 0 ]
#    then
#        echo "${serv} is stopped"
#        StartDaemon ${serv}
#        EchoResult "service ${serv} start"
#    else
#        echo "${serv} is running..."
#    fi
#
#    # check iptablesd start
#    StatusDaemon ${serv} && lsmod | grep ip_tables
#    EchoResult "${serv} : start"

    # tmpdir
    TMPDIR=/tmp/iptables$$
    mkdir ${TMPDIR}
    EchoResult "mkdir ${TMPDIR}"


}

##! @TODO:  iptables -L
##! @AUTHOR: huijing.hei
##! @VERSION: 1.0 
##! @OUT: 0 => success; 1 => failure

function DoTest()
{
    local TMPOUT=${TMPDIR}/tmpout
    # iptables -L
    iptables -L > ${TMPOUT} 2>&1
    EchoResult "iptables -L"

    # check
    local CHAINCNT=$(grep -c Chain ${TMPOUT})
    if [ $CHAINCNT -ne 3 ]; then
        echo "iptables -L failed to list rules."
        exit 1
    fi

    # iptables -vnL INPUT
    iptables -vnL INPUT > ${TMPOUT} 2>&1
    EchoResult "iptables -vnL INPUT"

    # check
    grep -c "Chain INPUT" ${TMPOUT}
    EchoResult "list INPUT rules"

    # iptables -t nat
    iptables -t nat -vnL  > ${TMPOUT} 2>&1
    EchoResult "iptables -t nat -vnL"

    # check
    CHAINCNT=$(grep -c Chain ${TMPOUT})
    if [ $CHAINCNT -lt 3 ]; then
        echo -e "\033[31m FAIL\033[0m | iptables -t nat failed to list rules."
        exit 1
    fi

}

##! @TODO: cleanup
##! @AUTHOR: huijing.hei
##! @VERSION: 1.0 
##! @OUT: 0 => success; 1 => failure

function DoCleanup()
{
    StopDaemon ${serv}
    EchoResult  "stop ${serv}"

    [ -e ${TMPDIR} ] && rm -rf ${TMPDIR}
}

# include lib files
if [ -z "$SFROOT" ]
then
    echo "SFROOT is null"
    exit 1
fi

. ${SFROOT}/lib/Echo.sh
. ${SFROOT}/lib/NetOps.sh

DoSetup
DoTest
EchoResult "testcase: select rules"
